{% extends "base.html" %}

{% block title %}任务详情 - XbyJob{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom" data-task-id="{% if task %}{{ task.id }}{% else %}null{% endif %}">
    <h1 class="h2">任务详情</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <a href="{{ url_for('dashboard.tasks') }}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-1"></i>返回列表
            </a>
            <button type="button" class="btn btn-success" onclick="executeTask()">
                <i class="fas fa-play me-1"></i>立即执行
            </button>
            <button type="button" class="btn btn-outline-danger" onclick="clearExecutions()">
                <i class="fas fa-trash me-1"></i>清除执行记录
            </button>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-8">
        <!-- 任务基本信息 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5><i class="fas fa-info-circle me-2"></i>基本信息</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>任务名称:</strong> <span id="taskName">-</span></p>
                        <p><strong>任务类型:</strong> <span id="taskType">-</span></p>
                        <p><strong>状态:</strong> <span id="taskStatus">-</span></p>
                        <p><strong>创建者:</strong> <span id="taskCreator">-</span></p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>Cron表达式:</strong> <code id="cronExpression">-</code></p>
                        <p><strong>超时时间:</strong> <span id="timeout">-</span>秒</p>
                        <p><strong>重试次数:</strong> <span id="retryAttempts">-</span></p>
                        <p><strong>创建时间:</strong> <span id="createdAt">-</span></p>
                    </div>
                </div>
                <div class="row" id="descriptionRow" style="display: none;">
                    <div class="col-12">
                        <p><strong>描述:</strong></p>
                        <p class="text-muted" id="taskDescription">-</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 执行记录 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5><i class="fas fa-history me-2"></i>执行记录</h5>
                <small class="text-muted" id="websocketStatus">
                    <i class="fas fa-circle text-success"></i> 实时连接
                </small>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped" id="executionsTable">
                        <thead>
                            <tr>
                                <th>执行ID</th>
                                <th>状态</th>
                                <th>开始时间</th>
                                <th>耗时</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="5" class="text-center">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- 分页 -->
                <nav aria-label="执行记录分页">
                    <ul class="pagination justify-content-center" id="pagination">
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <!-- 执行统计 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5><i class="fas fa-chart-bar me-2"></i>执行统计</h5>
            </div>
            <div class="card-body">
                <div class="row text-center mb-3">
                    <div class="col-12">
                        <h4 class="text-primary" id="totalExecutions">0</h4>
                        <small class="text-muted">总执行次数</small>
                    </div>
                </div>
                <div class="text-center mb-3">
                    <canvas id="statusChart" width="200" height="200"></canvas>
                </div>
                <div class="row text-center">
                    <div class="col-6">
                        <h6 class="text-success" id="successCount">0</h6>
                        <small class="text-muted">成功次数</small>
                    </div>
                    <div class="col-6">
                        <h6 class="text-danger" id="failedCount">0</h6>
                        <small class="text-muted">失败次数</small>
                    </div>
                </div>
                <div class="row text-center mt-2">
                    <div class="col-12">
                        <small class="text-muted">成功率: </small>
                        <span class="text-info" id="successRate">0%</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 调度信息 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5><i class="fas fa-clock me-2"></i>调度信息</h5>
            </div>
            <div class="card-body">
                <p><strong>下次执行:</strong><br><span id="nextRunAt" class="text-primary">-</span></p>
                <p><strong>最后执行时间:</strong><br><span id="lastRunAt">-</span></p>
                <p><strong>最后更新:</strong><br><span id="updatedAt">-</span></p>
            </div>
        </div>

        <!-- 环境配置 -->
        <div class="card" id="configCard" style="display: none;">
            <div class="card-header">
                <h5><i class="fas fa-cog me-2"></i>环境配置</h5>
            </div>
            <div class="card-body">
                <div id="workingDirectorySection" style="display: none;">
                    <p><strong>工作目录:</strong></p>
                    <code id="workingDirectory">-</code>
                </div>
                <div id="envVarsSection" style="display: none;">
                    <p><strong>环境变量:</strong></p>
                    <div id="envVars"></div>
                </div>

            </div>
        </div>
    </div>
</div>

<!-- 执行日志模态框 -->
<div class="modal fade" id="executionLogModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">执行日志</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <p><strong>任务名称:</strong> <span id="logTaskName">-</span></p>
                        <p><strong>执行ID:</strong> <code id="logExecutionId">-</code></p>
                        <p><strong>状态:</strong> <span id="logStatus">-</span></p>
                        <p><strong>退出码:</strong> <span id="logExitCode">-</span></p>
                        <p><strong>重试次数:</strong> <span id="logRetryCount">-</span></p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>开始时间:</strong> <span id="logStartTime">-</span></p>
                        <p><strong>结束时间:</strong> <span id="logEndTime">-</span></p>
                        <p><strong>执行时长:</strong> <span id="logDuration">-</span></p>
                        <p><strong>执行器:</strong> <span id="logExecutor">-</span></p>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h6><i class="fas fa-terminal me-1"></i>执行输出</h6>
                            <small class="text-muted" id="logWebsocketStatus">
                                <i class="fas fa-circle text-success"></i> 实时推送
                            </small>
                        </div>
                        <pre id="logOutput" class="bg-light p-3 rounded" style="max-height: 500px; overflow-y: auto; font-family: 'Courier New', monospace; font-size: 12px; white-space: pre-wrap; word-wrap: break-word; border: 1px solid #dee2e6;">加载中...</pre>
                        <div class="mt-2">
                            <small class="text-muted">
                                <i class="fas fa-info-circle me-1"></i>
                                此处显示任务执行的所有输出内容（包括标准输出和错误输出）
                            </small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary" onclick="downloadExecutionLog()">
                    <i class="fas fa-download me-1"></i>下载日志
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<!-- Socket.IO 客户端库 -->
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
<script type="text/javascript">
// Initialize variables
var taskId = document.querySelector('[data-task-id]').getAttribute('data-task-id');
if (taskId && taskId !== 'null') {
    taskId = parseInt(taskId);
} else {
    taskId = null;
}
var statusChart = null;
var currentPage = 1;
var socket = null;
var currentExecutionId = null;

$(document).ready(function() {
    // 测试调试输出功能
    debugLog('🚀 页面加载完成，开始初始化...', {taskId: taskId});
    
    // 总是初始化WebSocket，不管是否有taskId
    initWebSocket();
    
    if (taskId) {
        debugLog('📋 加载任务详情和执行记录...');
        loadTaskDetail();
        loadExecutions();
    } else {
        debugLog('⚠️ 没有taskId，跳过任务详情加载');
    }
    
    debugLog('✅ 页面初始化完成');
});

// WebSocket调试日志函数
function debugLog(message, data = null) {
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = `[WebSocket Debug ${timestamp}] ${message}`;
    
    // 输出到控制台
    if (data) {
        console.log(logEntry, data);
    } else {
        console.log(logEntry);
    }
}

// 初始化WebSocket连接
function initWebSocket() {
    try {
        debugLog('开始初始化WebSocket连接...');
        socket = io();
        
        socket.on('connect', function() {
            debugLog('✅ WebSocket连接成功', {socketId: socket.id});
            updateWebSocketStatus(true);
        });
        
        socket.on('disconnect', function() {
            debugLog('❌ WebSocket连接断开');
            updateWebSocketStatus(false);
        });
        
        socket.on('execution_status_change', function(data) {
            debugLog('📊 收到执行状态变化', data);
            handleExecutionStatusChange(data);
        });
        
        socket.on('execution_output', function(data) {
            debugLog('📝 收到执行输出', {
                execution_id: data.execution_id,
                output_type: data.output_type,
                content_length: data.content ? data.content.length : 0,
                is_realtime: data.is_realtime,
                current_execution: currentExecutionId
            });
            handleExecutionOutput(data);
        });
        
        socket.on('connect_error', function(error) {
            debugLog('❌ WebSocket连接错误', error);
        });
        
        socket.on('error', function(error) {
            debugLog('❌ WebSocket错误', error);
        });
        
        debugLog('WebSocket事件监听器已设置');
        
    } catch (error) {
        debugLog('❌ WebSocket初始化失败', error);
        updateWebSocketStatus(false);
    }
}

// 更新WebSocket连接状态显示
function updateWebSocketStatus(connected) {
    const statusElement = $('#websocketStatus');
    const logStatusElement = $('#logWebsocketStatus');
    
    if (connected) {
        statusElement.html('<i class="fas fa-circle text-success"></i> 实时连接');
        logStatusElement.html('<i class="fas fa-circle text-success"></i> 实时推送');
    } else {
        statusElement.html('<i class="fas fa-circle text-danger"></i> 连接断开');
        logStatusElement.html('<i class="fas fa-circle text-danger"></i> 连接断开');
    }
}

// 处理执行状态变化
function handleExecutionStatusChange(data) {
    debugLog('🔄 处理执行状态变化', {
        execution_id: data.execution_id,
        status: data.status,
        current_execution: currentExecutionId
    });
    
    // 刷新执行记录列表
    loadExecutions(currentPage);
    
    // 如果当前正在查看这个执行的日志，更新日志模态框
    if (currentExecutionId && currentExecutionId == data.execution_id) {
        debugLog('🔄 更新当前查看的执行详情');
        loadExecutionDetail(data.execution_id);
    }
}

// 处理实时输出
function handleExecutionOutput(data) {
    debugLog('📥 处理实时输出', {
        execution_id: data.execution_id,
        output_type: data.output_type,
        content_preview: data.content ? data.content.substring(0, 50) + '...' : 'null',
        current_execution: currentExecutionId,
        will_append: currentExecutionId && currentExecutionId == data.execution_id
    });
    
    // 如果当前正在查看这个执行的日志，实时更新输出
    if (currentExecutionId && currentExecutionId == data.execution_id) {
        debugLog('✅ 执行ID匹配，追加实时输出');
        appendRealtimeOutput(data);
    } else {
        debugLog('❌ 执行ID不匹配，跳过输出', {
            received_id: data.execution_id,
            current_id: currentExecutionId
        });
    }
}

// 追加实时输出到日志显示区域
function appendRealtimeOutput(data) {
    debugLog('📝 追加实时输出到界面', {
        output_type: data.output_type,
        content_length: data.content ? data.content.length : 0
    });
    
    const outputElement = $('#logOutput');
    if (outputElement.length > 0) {
        debugLog('✅ 找到日志输出元素');
        let currentContent = outputElement.text();
        
        if (data.output_type === 'stdout' && data.content) {
            // 直接追加标准输出
            currentContent += data.content;
            debugLog('📝 追加stdout内容');
        } else if (data.output_type === 'stderr' && data.content) {
            // 如果是第一次添加错误输出，添加分隔符
            if (currentContent && !currentContent.includes('--- 错误输出 ---')) {
                currentContent += '\n\n--- 错误输出 ---\n';
            }
            currentContent += data.content;
            debugLog('📝 追加stderr内容');
        }
        
        outputElement.text(currentContent);
        debugLog('✅ 内容已更新到界面');
        
        // 自动滚动到底部
        const outputDom = outputElement[0];
        if (outputDom) {
            outputDom.scrollTop = outputDom.scrollHeight;
            debugLog('📜 自动滚动到底部');
        }
    } else {
        debugLog('❌ 未找到日志输出元素 #logOutput');
    }
}

// 加入执行房间（当查看执行日志时）
function joinExecutionRoom(executionId) {
    debugLog('🏠 尝试加入执行房间', {
        execution_id: executionId,
        socket_connected: socket && socket.connected
    });
    
    if (socket && socket.connected) {
        socket.emit('join_execution', {execution_id: executionId});
        debugLog('✅ 已发送加入房间请求', {execution_id: executionId});
    } else {
        debugLog('❌ Socket未连接，无法加入房间');
    }
}

// 离开执行房间
function leaveExecutionRoom(executionId) {
    debugLog('🚪 尝试离开执行房间', {
        execution_id: executionId,
        socket_connected: socket && socket.connected
    });
    
    if (socket && socket.connected) {
        socket.emit('leave_execution', {execution_id: executionId});
        debugLog('✅ 已发送离开房间请求', {execution_id: executionId});
    } else {
        debugLog('❌ Socket未连接，无法离开房间');
    }
}

function loadTaskDetail() {
    $.get(`/api/tasks/${taskId}`)
        .done(function(response) {
            if (response.success) {
                renderTaskDetail(response.data);
            } else {
                showAlert('获取任务详情失败: ' + response.message, 'danger');
            }
        })
        .fail(function() {
            showAlert('网络错误，请稍后重试', 'danger');
        });
}

function renderTaskDetail(task) {
    $('#taskName').text(task.name);
    $('#taskType').html(getTaskTypeBadge(task.task_type));
    $('#taskStatus').html(task.is_enabled ? 
        '<span class="badge bg-success">已启用</span>' : 
        '<span class="badge bg-secondary">已禁用</span>');
    $('#taskCreator').text(task.creator || '-');
    $('#cronExpression').text(task.cron_expression);
    $('#timeout').text(task.timeout);
    $('#retryAttempts').text(task.retry_attempts);
    $('#createdAt').text(new Date(task.created_at).toLocaleString());
    
    if (task.description) {
        $('#taskDescription').text(task.description);
        $('#descriptionRow').show();
    }
    
    $('#commandOrScript').text(''); // command_or_script字段已移除
    
    // 调度信息
    $('#nextRunAt').text(task.next_run_at ? new Date(task.next_run_at).toLocaleString() : '-');
    $('#lastRunAt').text(task.last_started_at ? new Date(task.last_started_at).toLocaleString() : '-');
    $('#updatedAt').text(new Date(task.updated_at).toLocaleString());
    
    // 环境配置
    let hasConfig = false;
    
    if (task.working_directory) {
        $('#workingDirectory').text(task.working_directory);
        $('#workingDirectorySection').show();
        hasConfig = true;
    }
    
    if (task.environment_variables && Object.keys(task.environment_variables).length > 0) {
        renderEnvVars(task.environment_variables);
        $('#envVarsSection').show();
        hasConfig = true;
    }
    

    
    if (hasConfig) {
        $('#configCard').show();
    }
}

function loadExecutions(page = 1) {
    currentPage = page;
    
    // 显示刷新状态
    const refreshIcon = $('#autoRefreshStatus i');
    refreshIcon.removeClass('fa-spin').addClass('fa-pulse');
    
    $.get(`/api/tasks/${taskId}/executions?page=${page}`)
        .done(function(response) {
            if (response.success) {
                renderExecutions(response.data.executions);
                renderPagination(response.data.pagination);
                updateExecutionStats(response.data.stats);
            } else {
                showAlert('获取执行记录失败: ' + response.message, 'danger');
            }
        })
        .fail(function() {
            showAlert('网络错误，请稍后重试', 'danger');
        })
        .always(function() {
            // 恢复自动刷新状态
            setTimeout(function() {
                refreshIcon.removeClass('fa-pulse').addClass('fa-spin');
            }, 1000);
        });
}

function renderExecutions(executions) {
    const tbody = $('#executionsTable tbody');
    tbody.empty();
    
    if (executions.length === 0) {
        tbody.append(`
            <tr>
                <td colspan="5" class="text-center text-muted">暂无执行记录</td>
            </tr>
        `);
        return;
    }
    
    executions.forEach(function(execution) {
        const statusBadge = getStatusBadge(execution.status);
        const startTime = new Date(execution.started_at).toLocaleString();
        const duration = execution.duration ? formatDuration(execution.duration) : '-';
        
        // 构建操作按钮
        let actionButtons = `
            <button class="btn btn-sm btn-outline-primary" onclick="viewExecutionLog('${execution.execution_id}')" title="查看日志">
                <i class="fas fa-eye"></i>
            </button>
        `;
        
        // 如果是运行中的任务，添加停止按钮
        if (execution.status === 'running') {
            actionButtons += `
                <button class="btn btn-sm btn-outline-danger ms-1" onclick="stopExecution('${execution.execution_id}')" title="停止任务">
                    <i class="fas fa-stop"></i>
                </button>
            `;
        }
        
        tbody.append(`
            <tr>
                <td><code>${execution.execution_id}</code></td>
                <td>${statusBadge}</td>
                <td>${startTime}</td>
                <td>${duration}</td>
                <td>${actionButtons}</td>
            </tr>
        `);
    });
}

function updateExecutionStats(stats) {
    $('#totalExecutions').text(stats.total_executions);
    $('#successCount').text(stats.success_executions);
    $('#failedCount').text(stats.failed_executions);
    $('#successRate').text(stats.success_rate + '%');
    
    // 绘制饼图
    renderStatusChart(stats.success_executions, stats.failed_executions, stats.running_executions, stats.pending_executions);
}

function renderStatusChart(successCount, failedCount, runningCount, pendingCount) {
    const ctx = document.getElementById('statusChart').getContext('2d');
    
    if (statusChart) {
        statusChart.destroy();
    }
    
    const data = [];
    const labels = [];
    const colors = [];
    
    if (successCount > 0) {
        data.push(successCount);
        labels.push('成功');
        colors.push('#198754');
    }
    if (failedCount > 0) {
        data.push(failedCount);
        labels.push('失败');
        colors.push('#dc3545');
    }
    if (runningCount > 0) {
        data.push(runningCount);
        labels.push('运行中');
        colors.push('#007bff');
    }
    if (pendingCount > 0) {
        data.push(pendingCount);
        labels.push('等待中');
        colors.push('#ffc107');
    }
    
    if (data.length === 0) {
        // 没有数据时显示占位符
        data.push(1);
        labels.push('暂无数据');
        colors.push('#e9ecef');
    }
    
    statusChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: colors,
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
}

function viewExecutionLog(executionId) {
    debugLog('👁️ 开始查看执行日志', {
        new_execution_id: executionId,
        previous_execution_id: currentExecutionId
    });
    
    // 离开之前的执行房间
    if (currentExecutionId) {
        debugLog('🚪 离开之前的执行房间', {previous_id: currentExecutionId});
        leaveExecutionRoom(currentExecutionId);
    }
    
    // 获取具体的执行日志
    currentExecutionId = executionId;
    debugLog('🆔 设置当前执行ID', {execution_id: executionId});
    $('#logExecutionId').text(executionId);
    $('#executionLogModal').modal('show');
    debugLog('📱 显示日志模态框');
    
    // 重置日志内容
    $('#logOutput').text('加载中...');
    debugLog('🔄 重置日志内容为"加载中..."');
    
    // 加载执行详情
    debugLog('📋 开始加载执行详情');
    loadExecutionDetail(executionId);
    
    // 加入新的执行房间以接收实时更新
    debugLog('🏠 准备加入新的执行房间');
    joinExecutionRoom(executionId);
}

function loadExecutionDetail(executionId) {
    // 获取执行详情
    $.get(`/api/executions/${executionId}`)
        .done(function(response) {
            if (response.success) {
                const execution = response.data;
                window.currentExecutionLog = execution; // 保存当前执行记录供下载使用
                
                // 更新日志模态框内容
                $('#logTaskName').text(execution.task_name || '未知任务');
                $('#logExecutionId').text(execution.execution_id);
                $('#logStartTime').text(execution.started_at ? new Date(execution.started_at).toLocaleString() : '-');
                $('#logEndTime').text(execution.completed_at ? new Date(execution.completed_at).toLocaleString() : '-');
                $('#logStatus').html(getStatusBadge(execution.status));
                $('#logExitCode').text(execution.exit_code !== null ? execution.exit_code : '-');
                $('#logRetryCount').text(execution.retry_count || 0);
                $('#logDuration').text(execution.duration ? formatDuration(execution.duration) : '-');
                $('#logExecutor').text(execution.executor_host || '-');
                
                // 合并显示标准输出、错误输出和错误信息
                let combinedOutput = '';
                if (execution.stdout && execution.stdout.trim()) {
                    combinedOutput += execution.stdout;
                }
                if (execution.stderr && execution.stderr.trim()) {
                    if (combinedOutput) {
                        combinedOutput += '\n\n--- 错误输出 ---\n';
                    }
                    combinedOutput += execution.stderr;
                }
                if (execution.error_message && execution.error_message.trim()) {
                    if (combinedOutput) {
                        combinedOutput += '\n\n--- 错误信息 ---\n';
                    }
                    combinedOutput += execution.error_message;
                }
                
                if (!combinedOutput.trim()) {
                    combinedOutput = '暂无输出内容';
                }
                
                $('#logOutput').text(combinedOutput);
                
                // 自动滚动到底部
                const outputElement = document.getElementById('logOutput');
                if (outputElement) {
                    outputElement.scrollTop = outputElement.scrollHeight;
                }
                
            } else {
                showAlert('获取执行日志失败: ' + response.message, 'danger');
                $('#logOutput').text('获取日志失败: ' + response.message);
            }
        })
        .fail(function() {
            showAlert('网络错误，无法获取执行日志', 'danger');
            $('#logOutput').text('网络错误，无法获取执行日志');
        });
}



// 当模态框关闭时离开WebSocket房间
$('#executionLogModal').on('hidden.bs.modal', function () {
    if (currentExecutionId) {
        leaveExecutionRoom(currentExecutionId);
        currentExecutionId = null;
    }
});

function downloadExecutionLog() {
    if (!window.currentExecutionLog) {
        showAlert('没有可下载的日志', 'warning');
        return;
    }
    
    const execution = window.currentExecutionLog;
    
    // 创建日志内容
    const logContent = `任务执行日志
======================

任务名称: ${execution.task_name || '未知任务'}
执行ID: ${execution.execution_id}
状态: ${execution.status}
退出码: ${execution.exit_code !== null ? execution.exit_code : '-'}
重试次数: ${execution.retry_count || 0}
开始时间: ${execution.started_at ? new Date(execution.started_at).toLocaleString() : '-'}
结束时间: ${execution.completed_at ? new Date(execution.completed_at).toLocaleString() : '-'}
执行时长: ${execution.duration ? formatDuration(execution.duration) : '-'}
执行器: ${execution.executor_host || '-'}

=== 标准输出 ===
${execution.stdout || '无输出'}

=== 错误输出 ===
${execution.stderr || '无错误输出'}

=== 错误信息 ===
${execution.error_message || '无错误信息'}
`;
    
    // 下载文件
    const blob = new Blob([logContent], { type: 'text/plain; charset=utf-8' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `task_${taskId}_execution_${execution.execution_id}_log.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}

function clearExecutions() {
    if (!confirm('确定要清除该任务的所有执行记录吗？此操作不可恢复。')) {
        return;
    }
    
    $.ajax({
        url: `/api/tasks/${taskId}/executions/clear`,
        method: 'POST'
    })
    .done(function(response) {
        if (response.success) {
            showAlert('执行记录清除成功', 'success');
            // 重新加载执行记录
            loadExecutions(currentPage);
            // 重新加载统计信息
            loadTaskDetail();
        } else {
            showAlert('清除失败: ' + response.message, 'danger');
        }
    })
    .fail(function() {
        showAlert('网络错误，请稍后重试', 'danger');
    });
}

function editTask() {
    window.location.href = `/dashboard/tasks/${taskId}/edit`;
}

function executeTask() {
    $.ajax({
        url: `/api/tasks/${taskId}/execute`,
        method: 'POST'
    })
    .done(function(response) {
        if (response.success) {
            showAlert('任务已提交执行', 'success');
            setTimeout(function() {
                loadExecutions();
            }, 2000);
        } else {
            showAlert('执行失败: ' + response.message, 'danger');
        }
    })
    .fail(function() {
        showAlert('网络错误，请稍后重试', 'danger');
    });
}



function renderPagination(pagination) {
    const nav = $('#pagination');
    nav.empty();
    
    if (pagination.pages <= 1) return;
    
    // 上一页
    nav.append(`
        <li class="page-item ${!pagination.has_prev ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadExecutions(${pagination.page - 1})">上一页</a>
        </li>
    `);
    
    // 页码
    const startPage = Math.max(1, pagination.page - 2);
    const endPage = Math.min(pagination.pages, pagination.page + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        nav.append(`
            <li class="page-item ${i === pagination.page ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadExecutions(${i})">${i}</a>
            </li>
        `);
    }
    
    // 下一页
    nav.append(`
        <li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadExecutions(${pagination.page + 1})">下一页</a>
        </li>
    `);
}

function renderEnvVars(envVars) {
    const container = $('#envVars');
    container.empty();
    
    Object.entries(envVars).forEach(function([key, value]) {
        container.append(`
            <div class="mb-1">
                <code>${key}</code> = <code>${value}</code>
            </div>
        `);
    });
}


function getTaskTypeBadge(type) {
    const badges = {
        'python_script': '<span class="badge bg-primary">Python脚本</span>',
        'http_request': '<span class="badge bg-info">HTTP请求</span>',
        'sql_query': '<span class="badge bg-warning text-dark">SQL查询</span>'
    };
    return badges[type] || `<span class="badge bg-secondary">${type}</span>`;
}

function getStatusBadge(status) {
    const badges = {
        'success': '<span class="badge bg-success">成功</span>',
        'failed': '<span class="badge bg-danger">失败</span>',
        'running': '<span class="badge bg-primary">运行中</span>',
        'pending': '<span class="badge bg-warning">等待中</span>',
        'cancelled': '<span class="badge bg-secondary">取消</span>'
    };
    return badges[status] || `<span class="badge bg-secondary">${status}</span>`;
}

function formatDuration(seconds) {
    if (seconds < 60) {
        return seconds.toFixed(2) + '秒';
    } else if (seconds < 3600) {
        return Math.floor(seconds / 60) + '分' + Math.floor(seconds % 60) + '秒';
    } else {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        return hours + '小时' + minutes + '分';
    }
}

function stopExecution(executionId) {
    if (!confirm('确定要停止这个正在运行的任务吗？')) {
        return;
    }
    
    $.ajax({
        url: `/api/executions/${executionId}/stop`,
        method: 'POST'
    })
    .done(function(response) {
        if (response.success) {
            showAlert('任务已停止', 'success');
            // 刷新执行记录
            setTimeout(function() {
                loadExecutions(currentPage);
            }, 1000);
        } else {
            showAlert('停止失败: ' + response.message, 'danger');
        }
    })
    .fail(function() {
        showAlert('网络错误，请稍后重试', 'danger');
    });
}

function showAlert(message, type) {
    // 使用基础模板中定义的全局showMessage函数（即showToast）
    if (typeof window.showMessage === 'function') {
        // 映射类型到Toast支持的类型
        let toastType = type;
        switch(type) {
            case 'danger':
                toastType = 'error';
                break;
            case 'warning':
                toastType = 'warning';
                break;
            case 'success':
                toastType = 'success';
                break;
            default:
                toastType = 'info';
        }
        showMessage(message, toastType, 3000);
    } else {
        // 如果全局函数不可用，回退到原来的实现
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        $('.container-fluid').prepend(alertHtml);
        
        setTimeout(function() {
            $('.alert').alert('close');
        }, 3000);
    }
}
</script>
{% endblock %}